﻿using Adnc.Application.Shared.Services;
using Adnc.Infra.EventBus;
using Adnc.Infra.Helper;
using Adnc.Infra.IRepositories;
using Adnc.Shared.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WYT.Ord.Application.Contracts.Services;
using WYT.Ord.Repository.Entities;

namespace WYT.Ord.Application.Services
{
    internal class OrderTaskAppService : AbstractAppService, IOrderTaskAppService
    {
        private readonly IEfRepository<Order> _orderRepository;

        private readonly IEfRepository<OrderGoods> _orderGoodsRepository;

        private readonly IEventPublisher _eventPublisher;
        public OrderTaskAppService(IEfRepository<Order> orderRepository
            , IEfRepository<OrderGoods> orderGoodsRepository
            , IEventPublisher eventPublisher)
        {
            _orderRepository = orderRepository;
            _orderGoodsRepository = orderGoodsRepository;
            _eventPublisher = eventPublisher;
        }
        public async Task<AppSrvResult> OrderCheck()
        {
            var orders = await _orderRepository.Where(x => x.SendTime <= DateTime.Now.AddDays(-14) && x.State == 3).ToListAsync();
            foreach (var item in orders)
            {
                var goods = await _orderGoodsRepository.Where(x => x.OrderId == item.Id).ToListAsync();
                if (!goods.Any(x => x.State == 0))
                {
                    item.State = 4;
                    item.ConfirmTime = DateTime.Now;

                    await _orderRepository.UpdateAsync(item, UpdatingProps<Order>(x => x.State, x => x.ConfirmTime));
                    await _orderGoodsRepository.UpdateRangeAsync(x => x.OrderId == item.Id && x.State == 1, y => new OrderGoods { State = 2, ConfirmTime = DateTime.Now });

                    //发布订单收货完成事件
                    var eventId = IdGenerater.GetNextId();
                    var eventData = new OrderReceivingEvent.EventData() { OrderId = item.Id };
                    var eventSource = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;
                    await _eventPublisher.PublishAsync(new OrderReceivingEvent(eventId, eventData, eventSource));
                }
            }

            return AppSrvResult();
        }
    }
}
